package it.sd.utility;

import java.io.InputStream;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

public class XMLWrapperFactory {
	
	
	private static DocumentBuilder getBuilder() throws Exception {
		DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
		domFactory.setNamespaceAware(true); 
		return domFactory.newDocumentBuilder();
	}
	
	public static XMLWrapper build(String rootTag) throws Exception {
		Document document = getBuilder().newDocument();
		Element root = document.createElement(rootTag);
		document.appendChild(root);
		return new XMLWrapper(document);
	}
	
	public static XMLWrapper parse(String xml) throws Exception  {
		InputSource source = new InputSource(new StringReader(xml));
		Document document = getBuilder().parse(source);
		return new XMLWrapper(document);
	}
	
	public static XMLWrapper parse(InputStream is) throws Exception  {
		Document document = getBuilder().parse(is);
		is.close();
		return new XMLWrapper(document);
	}	

}